package com.imooc.sell.service.impl;

import com.imooc.sell.dataobject.ProductInfo;
import com.imooc.sell.dto.CartDTO;
import com.imooc.sell.enums.ProductStatusEnum;
import com.imooc.sell.enums.ResultEnum;
import com.imooc.sell.exception.SellException;
import com.imooc.sell.repository.ProductInfoRepository;
import com.imooc.sell.service.ProductInfoService;
import net.bytebuddy.implementation.bytecode.Throw;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ProductInfoServiceimpl implements ProductInfoService {

  @Autowired
  private ProductInfoRepository repository;

  @Override
  public ProductInfo findOne(String productId) {
    return repository.findById(productId).orElse(null);
  }

  @Override
  public List<ProductInfo> findUpAll() {
    return repository.findByProductStatus(ProductStatusEnum.UP.getCode());
  }

  @Override
  public Page<ProductInfo> findAll(Pageable pageable) {
    return repository.findAll(pageable);
  }

  @Override
  public ProductInfo save(ProductInfo productInfo) {
    return repository.save(productInfo);
  }

  @Override
  @Transactional
  public void increaseStock(List<CartDTO> cartDTOList) {
    //判断商品是否存在
    for (CartDTO cartDTO : cartDTOList) {
      ProductInfo productInfo = findOne(cartDTO.getProductId());
      if (productInfo == null) {
        throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
      }
      //计算出新的库存，更新数据库
      productInfo.setProductStock(productInfo.getProductStock() + cartDTO.getProductQuantity());
      repository.save(productInfo);
    }
  }

  @Override
  @Transactional
  public void decreaseStock(List<CartDTO> cartDTOList) {
    for (CartDTO cartDTO : cartDTOList) {
      ProductInfo productInfo = findOne(cartDTO.getProductId());
      //商品未找到
      if (productInfo == null) {
        throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
      }
      //判断库存是否充足
      Integer result = productInfo.getProductStock() - cartDTO.getProductQuantity();
      if (result < 0) {
        throw new SellException(ResultEnum.PRODUCT_STOCK_EMPTY);
      }
      //写入扣除之后的库存
      productInfo.setProductStock(result);
      repository.save(productInfo);
    }
  }
}
